<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Thread_model extends DQ_Model 
{
    public function __construct()
    {
        parent::__construct();
    }

    public function addThread()
    {
        $checkedData = $this->checkInput(__FUNCTION__,0);

        $checkedData['authorid'] = $this->checkUser();
        $checkedData['dateline'] = date('Y-m-d H:i:s');
        $checkedData['endtime'] = date('Y-m-d H:i:s');

        $keys = array_flip(getFid());
        $checkedData['message'] = $this->_createMessage($checkedData['playtime'],$checkedData['friends'],$checkedData['fid']);

        $res = $this->_addThread($checkedData);

        return $res;
    }

    private function _checkUserExistThread($uid,$start)
    {
        $this->db->where('playtime <= ',date('Y-m-d H:i',strtotime($start) + 3600 * 2));
        $this->db->where('playtime >= ',date('Y-m-d H:i',strtotime($start) - 3600 * 2));
        $this->db->where('authorid',$uid);

        $this->db->from('forum_thread');
        return $this->db->count_all_results();
    }

    private function _addThread($data)
    {
        //检测用户已有活动，时间是否有冲突
        $num = $this->_checkUserExistThread($data['authorid'],$data['playtime']);

        if($num > 0)
        {
            return array('error'=>3100,'msg'=>$this->error_code[3100],'data'=>$num);
        }

        $this->db->trans_begin();

        $this->db->insert('forum_thread',array(
            'fid'=>$data['fid'],
            'authorid'=>$data['authorid'],
            'lastpost'=>$data['authorid'],
            'subject'=>$data['subject'],
            'playtime'=>$data['playtime'],
            'endtime'=>$data['endtime'],
            'dateline'=>$data['dateline'],
            'address'=>$data['address'],
            'realaddress'=>$data['realaddress'],
            'tip'=>$data['tip'],
            'invite'=>$data['friends'],
            'cityid'=>$data['cityid'],
            'longitude'=>$data['longitude'],
            'latitude'=>$data['latitude']
        ));
        $tid = $this->db->insert_id();

        $this->db->insert('forum_post',array(
            'tid'=>$tid,
            'fid'=>$data['fid'],
            'authorid'=>$data['authorid'],
            'dateline'=>$data['dateline'],
            'first'=>1,
            'message'=>$data['message'],
            'longitude'=>$data['longitude'],
            'latitude'=>$data['latitude'],
            'userip'=>$this->input->ip_address()
        ));

        if($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return array('error'=>3004,'msg'=>$this->error_code[3004],'data'=>0);
        }
        else
        {
            //数据入mongodb
            $mdata = array('fid'=>intval($data['fid']),'tid'=>$tid,'cityid'=>intval($data['cityid']),'start'=>strtotime($data['playtime']),'gps'=>array('lat'=>$data['latitude'],'lng'=>$data['longitude']));
            $this->load->library('Mongodbkit');

            try
            {
                $insert_ok = $this->mongodbkit->insert($mdata);

                if($insert_ok)
                {
                    $this->db->trans_commit();
                    return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$tid);
                }
                else
                {
                    $this->db->trans_rollback();
                    return array('error'=>3005,'msg'=>$this->error_code[3005],'data'=>0);
                }
            }
            //防止mongodb故障
            catch(Exception $e)
            {
                $this->db->trans_rollback();
                return array('error'=>3005,'msg'=>$this->error_code[3005],'data'=>0);
            }
        }

    }

    public function addPost()
    {
        $checkedData = $this->checkInput(__FUNCTION__,0);

        $checkedData['authorid'] = $this->checkUser();
        $checkedData['dateline'] = date('Y-m-d H:i:s');

        $res = $this->_addPost($checkedData);

        return $res;
    }

    private function _addPost($data)
    {
        $this->db->trans_begin();

        $this->db->insert('forum_post',array(
            'tid'=>$data['tid'],
            'fid'=>$data['fid'],
            'authorid'=>$data['authorid'],
            'dateline'=>$data['dateline'],
            'first'=>0,
            'message'=>$data['message'],
            //'longitude'=>$data['longitude'],
            //'latitude'=>$data['latitude'],
            'longitude'=>0,
            'latitude'=>0,
            'userip'=>$this->input->ip_address()
        ));

        $insert_id = $this->db->insert_id();
        $this->db->where('tid',$data['tid']);
        $this->db->set('replies', 'replies+1', FALSE);
        $this->db->set('lastpost', $data['authorid']);
        $this->db->update('forum_thread');
        $update_num = $this->db->affected_rows();

        if($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return array('error'=>3006,'msg'=>$this->error_code[3006],'data'=>0);
        }
        else
        {
            //成功更新了正确的帖子
            if($update_num && $insert_id )
            {
                $this->db->trans_commit();
                return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$insert_id);
            }
            else
            {
                $this->db->trans_rollback();
                return array('error'=>3006,'msg'=>$this->error_code[3006],'data'=>0);
            }
        }
    }

    public function getThreadNearby($show_number = 30)
    {
        $checkedData = $this->checkInput(__FUNCTION__);

        $now = time() + 15 * 60;    //活动开始前15分钟的显示

        //获取周边尚未结束的活动tid
        $this->load->library('Mongodbkit');

        if($checkedData['fid'])
        {
            $query = array("fid"=>(int) $checkedData['fid'],"cityid"=>(int) $checkedData['cityid'],"start"=>array('$gt'=>$now),"gps"=>array('$near'=>array($checkedData['lat'],$checkedData['lng'])));
        }
        else
        {
            $query = array("cityid"=>(int) $checkedData['cityid'],"start"=>array('$gt'=>$now),"gps"=>array('$near'=>array($checkedData['lat'],$checkedData['lng'])));
        }

        $res = $this->mongodbkit->find($query,array('tid'),$show_number);

        if(!empty($res))
        {
            $tids = array();
            foreach($res as $value)
            {
                $tids[] = $value['tid'];
            }

            //获取简略帖子数据
            $threads = $this->_getThreadByTids($tids,0);
            if(empty($threads))
            {
                return array('error'=>1001,'msg'=>$this->error_code[1001],'data'=>array());
            }
            else
            {
                return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$threads);
            }
        }
        else
        {
            return array('error'=>1001,'msg'=>$this->error_code[1001],'data'=>array());
        }
    }

    private function _getThreadByTids($tids,$full=0)
    {
        if(!$full)
        {
            $this->db->select('username,score,fid,tid,authorid,subject,playtime,endtime,address,longitude,latitude');
        }

        $this->db->from('forum_thread');
        $this->db->join('uc_member', 'uc_member.uid = forum_thread.authorid');

        $this->db->where_in('tid',$tids);
        $query = $this->db->get();
        
        $threads = $query->result_array();

        $apply_num = array();
        $this->db->select('count(*) as num,tid');
        $this->db->from('thread_apply');
        $this->db->group_by('tid'); 
        $query = $this->db->get();

        foreach($query->result_array() as $value)
        {
            $apply_num[$value['tid']] = $value['num'];
        }

        foreach($threads as $key=>$value)
        {
            if(isset($apply_num[$value['tid']]))
            {
                $threads[$key]['apply_num'] = $apply_num[$value['tid']]; 
            }
            else
            {
                $threads[$key]['apply_num'] = 0;
            }
        }

        return $threads;
    }

    public function getThreadSummary()
    {
        $checkedData = $this->checkInput(__FUNCTION__);

        $this->db->select('forum_thread.*,forum_post.*,username');
        $this->db->from('forum_thread');
        $this->db->join('forum_post', 'forum_thread.tid = forum_post.tid');
        $this->db->join('uc_member', 'uc_member.uid = forum_thread.authorid');
        $this->db->where('forum_thread.tid',$checkedData['tid']);
        $this->db->where('forum_post.first',1);
        $this->db->where('forum_thread.status',0);

        $query = $this->db->get();
        $summary = $query->row_array();

        if(empty($summary))
        {
            return array('error'=>1001,'msg'=>$this->error_code[1001],'data'=>array());
        }
        else
        {
            $summary['apply_num'] = $this->_getJoinedPeople($checkedData['tid']);
            return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$summary);
        }
    }

    public function getThreadDetail()
    {
        $checkedData = $this->checkInput('getThreadSummary');
        
        $this->db->where('tid',$checkedData['tid']);
        $this->db->where('status',0);
        $query = $this->db->get('forum_thread');

        $thread = $query->row_array();

        if(empty($thread))
        {
            return array('error'=>1001,'msg'=>$this->error_code[1001],'data'=>array());
        }
        else
        {
            $thread['apply_num'] = $this->_getJoinedPeople($checkedData['tid']);
            $posts = $this->_getDiscuss($checkedData['tid']);
            return array('error'=>0,'msg'=>$this->error_code[0],'data'=>array('thread'=>$thread,'posts'=>$posts));
        }
    }

    public function getDiscuss()
    {
        $checkedData = $this->checkInput(__FUNCTION__);
        $posts = $this->_getDiscuss($checkedData['tid'],$checkedData['from'],$checkedData['limit']);

        if(empty($posts))
        {
            return array('error'=>1001,'msg'=>$this->error_code[1001],'data'=>array());
        }
        else
        {
            return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$posts);
        }
    }

    private function _getDiscuss($tid,$from=0,$limit=20)
    {
        $this->db->where('tid',$tid);
        $this->db->where('first',0);
        $this->db->where('status',0);
        $this->db->order_by('dateline','desc');
        $query = $this->db->get('forum_post',$limit,$from);

        $post = $uids = array();
        foreach($query->result_array() as $value)
        {
            $post[] = $value;
            $uids[] = $value['authorid'];
        }

        if($post)
        {
            $this->load->model('user_model');
            $userInfo = $this->user_model->getUserInfoByIds($uids,array('username','uid','status','gender'));

            foreach($post as $key=>$value)
            {
                $post[$key]['userInfo'] = $userInfo[$value['authorid']];
            }
        }

        return $post;
    }

    //目前返回参与的人数
    public function getJoinedPeople($data=array())
    {
        if($data)
        {
            $checkedData = $data;
        }
        else
        {
            $checkedData = $this->checkInput('getThreadSummary');
        }

        $joined = $this->_getJoinedPeople($checkedData['tid']);

        return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$joined);
    }

    private function _getJoinedPeople($tid)
    {
        $this->db->where('tid',$tid);
        $query = $this->db->get('thread_apply');
        return $query->result_array();
    }

    public function joinActivity()
    {
        $checkedData = $this->checkInput('getThreadSummary');
        $checkedData['authorid'] = $this->checkUser();
        
        if($this->_isJoined($checkedData['authorid'],$checkedData['tid']))
        {
            return array('error'=>3001,'msg'=>$this->error_code[3001],'data'=>1);
        }
        else
        {
            //判断该活动是否可以加入
            $this->db->select('tid,playtime');
            $this->db->where('tid',$checkedData['tid']);
            $this->db->where('status',0);
            $query  = $this->db->get('forum_thread');
            $thread = $query->row_array();
            
            if($thread)
            {
                //活动已开始
                if(strtotime($thread['playtime']) < time())
                {
                    return array('error'=>3007,'msg'=>$this->error_code[3007],'data'=>0);
                }

                $this->db->insert('thread_apply',array(
                    'tid'=>$checkedData['tid'],
                    'uid'=>$checkedData['authorid'],
                ));

                if($this->db->insert_id())
                {
                    return array('error'=>0,'msg'=>$this->error_code[0],'data'=>1);
                }
                else
                {
                    return array('error'=>3002,'msg'=>$this->error_code[3002],'data'=>0);
                }

            }
            else
            {
                return array('error'=>3003,'msg'=>$this->error_code[3003],'data'=>0);
            }

        }
    }

    public function unjoin()
    {
        $checkedData = $this->checkInput('getThreadSummary');
        $checkedData['authorid'] = $this->checkUser();

        //判断该活动是否可以离开
        $this->db->select('tid,playtime');
        $this->db->where('tid',$checkedData['tid']);
        $this->db->where('status',0);
        $query  = $this->db->get('forum_thread');
        $thread = $query->row_array();

        if($thread && strtotime($thread['playtime']) > time())
        {
            $this->db->where('tid',$checkedData['tid']);
            $this->db->where('uid',$checkedData['authorid']);
            $this->db->delete('thread_apply');

            return array('error'=>0,'msg'=>$this->error_code[0],'data'=> $this->db->affected_rows());
        }
        else
        {
            return array('error'=>3008,'msg'=>$this->error_code[3008],'data'=>0);
        }
    }

    public function isJoined()
    {
        $checkedData = $this->checkInput(__FUNCTION__);

        $num = $this->_isJoined($checkedData['uid'],$checkedData['tid']);
        return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$num);
    }

    private function _isJoined($uid,$tid)
    {
        $this->db->where('tid',$tid);
        $this->db->where('uid',$uid);
        $this->db->from('thread_apply');
        $num = $this->db->count_all_results();

        return $num;
    }

    //帖子列表
    public function getMyThreads($data=array())
    {
        if($data)
        {
            $checkedData = $data;
        }
        else
        {
            $checkedData = $this->checkInput(__FUNCTION__);
        }


        if($checkedData['fid'])
        {
            $this->db->where('fid',$checkedData['fid']);
        }

        $this->db->where('authorid',$checkedData['authorid']);
        $this->db->order_by('dateline','desc');
        $query = $this->db->get('forum_thread',$checkedData['limit'],$checkedData['from']);

        return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$query->result_array());
    }

    private function _createMessage($playtime,$friends,$fid)
    {
        $keys = array_flip(getFid());
        return sprintf(ACTIVITY_MESSAGE,date('m月d日h:i',strtotime($playtime)),$friends,$keys[$fid]);
    }

    /*
    //生成城市js
    public function create_city_id()
    {
        $where = 'id <= 4 or area_name like "%市%"';
        $this->db->where($where);
        $this->db->from('area');
        $query = $this->db->get();

        echo 'var cityIds = {';
        foreach($query->result_array() as $value)
        {
            if(mb_substr($value['area_name'],-1) == '市')
            {
                $value['area_name'] = mb_substr($value['area_name'],0,-1);
            }
            echo '"'.$value['area_name'].'":'.$value['id'].",";
        }

        echo '}';
    }
    */
}
